import json
from django.views import View
from django.http import JsonResponse

from rbac.models import Roles


class Role(View):

    def get(self, request):
        query = request.GET
        role_name = query.get("role_name")
        role_code = query.get("role_code")
        status = query.get("status")

        role = Roles.objects
        # 获取用户列表数据的内容
        if (role_name):
            role = role.filter(role_name__contains=role_name)

        if (role_code):
            role = role.filter(role_code__contains=role_code)

        if (status):
            role = role.filter(status=status)

        role = role.values('id', 'role_name', 'status', 'role_code', 'order')

        return JsonResponse({
            'code': 200,
            'data': list(role),
            'msg': "获取列表数据成功",
            'total': len(list(role))
        })

    def post(self, request):
        try:
            # 获取数据内容
            body = json.loads(request.body)
            print(body)
            role_name = body.get("role_name")
            role_code = body.get("role_code")
            order = body.get("order")
            status = body.get("status")

            Roles.objects.create(role_name=role_name,role_code=role_code,order=order,status=status)
            return JsonResponse({
                'code': 200,
                'msg': "创建角色数据成功"
            })

        except Exception as err:
            return JsonResponse({
                'status': "error",
                'msg': format(err)
            })
